package com.soft.javase.day15.reflects;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.util.stream.Stream;

/**
 * @author yzg
 * @desc TODO
 * @date 2025/5/27
 */
public class ReflectDemo {
    public static void main(String[] args) {
        Student student = new Student("张三", 100, 20);
        Teacher teacher = new Teacher("李四", 10, "计算机");

        print(student);
        print(teacher);
    }

    public static void print(Object obj) {
        try (PrintStream ps = new PrintStream(new FileOutputStream("obj.txt",true))) {
            System.setOut(ps);
            Class<?> clazz = obj.getClass();
            Field[] fields = clazz.getDeclaredFields();
            System.out.println("----------"+clazz.getSimpleName()+"----------");
            Stream.of(fields).forEach(field -> {
                field.setAccessible(true);
                try {
                    System.out.println(field.getName()+" - " +field.get(obj));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
